import { interceptorsResponse } from '@/page/layout/core/net/interceptors.response';
import { interceptorsRequest } from '@/page/layout/core/net/interceptors.request';
import environment from '@/environments/environment';
import axios from 'axios';
import { apis } from './api'


// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    console.log(config)
    // 在发送请求之前做些什么
    let configb =  interceptorsRequest(config)
    return configb;
}, function (error) {
    let vinterceptorsRequest =  interceptorsRequest(error)
    // 对请求错误做些什么
    return Promise.reject(vinterceptorsRequest);
});


// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    let intercetor = new interceptorsResponse(response)
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    let intercetor = new interceptorsResponse(error.response)
    return Promise.reject(intercetor);
});


// console.log(import.meta.env.DEV, import.meta.env.PROD,import.meta.env.MODE)

//请求方法
type methods = 'get' | 'post' | 'delete' | 'put' | 'patch'
const methods: Array<methods> = ["get", "post", "delete", "put", "patch"];
/*
    请求方式
    post('请求地址url','请求附加地址','请求参数')
    get('请求地址url','请求附加地址','请求参数')
*/
export const [get, post, del, put, patch] = methods.map((action: methods) => {
    return (road: string, data: string | '', params: string | { [key: string]: any } | '') => {
        return axios({
            method: action,
            url: reqRoad(action, road, data, params),
            data: action !== 'get' ? params : null,
        }).then(res => {
            return res.data
        }).catch((error) =>{
            console.log(error)
        })
    }
})


const parseUrl = (url: any, params: string) => {
    if (JSON.stringify(params) == "{}" || params == '') {
        return url;
    } else {
        return url + params;
    }
}
const serialize = function (obj: { [key: string]: any }) {

    var str = [];
    for (var p in obj)
        if (obj.hasOwnProperty(p) && obj[p]) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
    return str.join("&");
}

const reqRoad = (method: string, road: string, data: string, params: string | { [key: string]: any }) => {
    if (method === 'get' && params) {
        // console.log(baseUrl[import.meta.env.MODE] + parseUrl(apis[road], data) + '?' + serialize(params));
        return environment.api.baseUrl + parseUrl(apis[road], data) + '?' + serialize(params as { [key: string]: any })
    } else {
        return environment.api.baseUrl + parseUrl(apis[road], data)
    }
}



